package com.crawler.waf.clientcache;

import javax.servlet.http.HttpServletRequest;


import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.LastModified;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import com.crawler.waf.annotations.LastModifiedCache;

public class LastModifiedRequestMappingHandlerAdapter extends RequestMappingHandlerAdapter   {
	
	@Override
	protected long getLastModifiedInternal(HttpServletRequest request, HandlerMethod handlerMethod) {
		if (handlerMethod instanceof LastModified) {
			return ((LastModified) handlerMethod).getLastModified(request);
		}		
		if(enabledLastModifiedCache(request, handlerMethod)){
			return System.currentTimeMillis();
		}
		return -1L;
	}
	
	
	protected final boolean enabledLastModifiedCache(
			final HttpServletRequest request, 
			final Object handler) {
		
		if (handler == null || !(handler instanceof HandlerMethod)) {
			return false;
		}
		
		final HandlerMethod handlerMethod = (HandlerMethod) handler;
		LastModifiedCache lastModified = handlerMethod.getMethodAnnotation(LastModifiedCache.class);
		
		if (lastModified == null) {
			if(handlerMethod.getBeanType().isAnnotation())
				return handlerMethod.getBeanType().getAnnotation(LastModifiedCache.class).enabled();
			else 
				return false;
		}
		
		return lastModified.enabled();
	}

}
